package problems

import "sort"

// ParkingSystem 1603
// https://leetcode-cn.com/problems/design-parking-system/
type ParkingSystem struct {
	big, medium, small int
}

func ConstructorParkingSystem(big int, medium int, small int) ParkingSystem {
	return ParkingSystem{big, medium, small}
}

func (s *ParkingSystem) AddCar(carType int) bool {
	switch carType {
	case 1:
		if s.big > 0 {
			s.big--
			return true
		}
	case 2:
		if s.medium > 0 {
			s.medium--
			return true
		}
	case 3:
		if s.small > 0 {
			s.small--
			return true
		}
	}
	return false
}

// RestoreMatrix 1605
// https://leetcode-cn.com/problems/find-valid-matrix-given-row-and-column-sums/
func RestoreMatrix(rowSum []int, colSum []int) [][]int {
	m, n, jIndex := len(rowSum), len(colSum), 0
	res := make([][]int, m)
	for i := 0; i < m; i++ {
		res[i] = make([]int, n)
		for j := jIndex; j < n; j++ {
			if rowSum[i] < colSum[j] {
				res[i][j] = rowSum[i]
			} else {
				res[i][j] = colSum[j]
			}
			rowSum[i], colSum[j] = rowSum[i]-res[i][j], colSum[j]-res[i][j]
			if rowSum[i] == 0 {
				break
			}
			if colSum[j] == 0 {
				jIndex = j
			}
		}
	}
	return res
}

// SpecialArray 1608
// https://leetcode.cn/problems/special-array-with-x-elements-greater-than-or-equal-x/
func SpecialArray(nums []int) int {
	sort.Ints(nums)
	size := len(nums)

	for i := 1; i <= size; i++ {
		if i <= nums[size-i] && (i == size || i > nums[size-i-1]) {
			return i
		}
	}

	return -1
}
